<template>
  <div>
    <el-switch
      v-model="draggable"
      active-color="#13ce66"
      inactive-color="#ff4949"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    ></el-switch>
    <el-button @click="batchSave()" type="success" size="mini" round v-if="draggable">保存</el-button>
    <el-button @click="batchDelete()" type="danger" size="mini" round>删除</el-button>
    <el-tree
      node-key="catId"
      :data="menus"
      :props="defaultProps"
      @node-click="handleNodeClick"
      show-checkbox
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="() => edit(data)">修改</el-button>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">增加</el-button>
          <el-button
            v-if="node.childNodes.length==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >删除</el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="category" label-width="80px" size="mini">
        <el-form-item label="分类名称">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
        <el-form-item label="分类图标">
          <el-input v-model="category.icon"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCategory()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      menus: [],
      title: "",
      expandedKey: [],
      dialogVisible: false,
      defaultProps: {
        children: "children",
        label: "name"
      },
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: "",
        catId: null
      },
      categoryAddOrEditTitleArray: ["新增分类", "修改分类"],
      maxLevel: 0,
      updateNodes: [],
      draggable: true,
      parentCid: []
    };
  },
  /* 生命周期 - 创建完成（访问当前this实例） */
  created() {
    this.getMenus();
  },

  /* 生命周期 - 挂载完成（访问DOM元素） */
  mounted() {},

  /* 方法 */
  methods: {
    /* 保存或者修改分类 */
    submitCategory() {
      if (this.category.catId == null) {
        //保存
        this.addCategory();
      } else {
        //修改
        this.editCategory();
      }
    },

    /* 修改分类 */
    editCategory() {
      var { catId, name, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false)
      }).then(({ data }) => {
        this.dialogVisible = false;
        if (data && data.code === 0) {
          this.$message({
            type: "success",
            message: `菜单修改成功!`
          });
          this.getMenus();
          this.expandedKey = [this.category.parentCid];
        }
      });
    },

    /* 添加分类 */
    addCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.dialogVisible = false;
        if (data && data.code === 0) {
          this.$message({
            type: "success",
            message: `菜单保存成功!`
          });
          this.getMenus();
          this.expandedKey = [this.category.parentCid];
        }
      });
    },

    /* 获取分类数据 */
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list"),
        method: "post"
      }).then(({ data }) => {
        this.menus = data.data;
      });
    },
    handleNodeClick(data) {
      console.log(data);
    },

    /* 修改菜单 */
    edit(data) {
      this.title = this.categoryAddOrEditTitleArray[1];
      this.dialogVisible = true;
      this.$http({
        url: this.$http.adornUrl("/product/category/info/" + data.catId),
        method: "get"
      }).then(({ data }) => {
        console.log(data);
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;
      });
    },

    /* 新增菜单 */
    append(data) {
      this.title = this.categoryAddOrEditTitleArray[0];
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.sort = 0;
      this.category.showStatus = 1;
      this.category.catId = null;
    },

    /* 删除菜单 */
    remove(node, data) {
      var ids = [data.catId];
      this.$confirm(
        "此操作将永久删除【" + data.name + "】菜单, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.getMenus();
            this.$message({
              type: "success",
              message: `菜单删除成功`
            });
            this.expandedKey = [node.parent.data.catId];
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消删除${data.name}`
          });
        });
    },

    /* 拖拽时判定目标节点能否被放置。type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后 
     *
     * inner:A节点往B节点里面放，计算当前节点的最大深度：deep，减去当前节点的深度，再+1，为当前节点以下的层级深度
     * 如果层级深度+B节点的当前的深度 <= 3 那么可以放，否则不能。

     * next/pre:A节点往B节点前或者后放，层级深度 + B节点的父节点的深度 <= 3 那么可以放，否则不能。
    
    */
    allowDrop(draggingNode, dropNode, type) {
      this.maxLevel = 0;
      if (
        draggingNode.data.children == null ||
        draggingNode.data.children.length == 0
      ) {
        //如果本身没有子节点
        this.maxLevel = draggingNode.level;
      } else {
        this.countNodeLevel(draggingNode);
      }
      let deep = this.maxLevel - draggingNode.level + 1;
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },

    /* 拖拽成功完成时触发的事件
     * 共四个参数，依次为：被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置（before、after、inner）、event
     */
    handleDrop(draggingNode, dropNode, dropType, ev) {
      //获取当前节点最新的父节点ID
      let parentCid = 0;
      //当前节点最新的兄弟节点
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        parentCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        parentCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }

      //当前节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //当前拖拽节点
          let catLevel = draggingNode.data.catLevel;
          if (siblings[i].level != draggingNode.level) {
            //修改当前节点的层级catLevel
            catLevel = siblings[i].level;
            //修改子节点的层级catLevel
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: parentCid,
            catLevel: catLevel
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      this.parentCid.push(parentCid);
      console.log(this.parentCid);
    },

    /* 批量删除*/
    batchDelete() {
      let checkNodes = this.$refs.tree.getCheckedNodes();
      if (checkNodes == null || checkNodes.length == 0) {
        this.$message({
          type: "error",
          message: `请至少选择一个分类`,
          duration: 1000
        });
        return false;
      }
      let catIds = [];
      let names = [];
      for (let i = 0; i < checkNodes.length; i++) {
        catIds.push(checkNodes[i].catId);
        names.push(checkNodes[i].name);
      }

      this.$confirm(
        "此操作将批量删除【" + names + "】菜单, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false)
          }).then(({ data }) => {
            this.getMenus();
            this.$message({
              type: "success",
              message: `菜单批量删除成功`
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消删除`
          });
        });
    },

    /* 批量保存拖拽后的更新节点 */
    batchSave() {
      //更新后台数据
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: `菜单顺序修改成功`
        });
        this.getMenus();
        this.expandedKey = this.parentCid;
        //清空maxLevel和updateNodes
        this.maxLevel = 0;
        this.updateNodes = [];
      });
    },

    /* 更新子节点的catLevel */
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },

    /* 获取当前节点的最大深度 */
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let index = 0; index < node.childNodes.length; index++) {
          if (node.childNodes[index].level > this.maxLevel) {
            this.maxLevel = node.childNodes[index].level;
          }
          this.countNodeLevel(node.childNodes[index]);
        }
      }
    }
  }
};
</script>

<style scoped>
/* @import url(); 引入css类[样式] */
</style>


